package com.imooc.pan.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.imooc.pan.config.AlipayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Mr.M
 * @version 1.0
 * @description 扫码支付的测试
 * @date 2023/2/25 16:17
 */

@Controller
public class PayTestController {
    
    //下单接口测试
    @RequestMapping("/alipaytest")
    public void doPost(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse) throws ServletException, IOException, AlipayApiException {
/*
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, APP_ID, APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
//        alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
        alipayRequest.setNotifyUrl("http://tjxt-user-t.itheima.net/xuecheng/orders/paynotify");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"202303200101020011\"," +
                "    \"total_amount\":0.1," +
                "    \"subject\":\"Iphone14 16G\"," +
                "    \"product_code\":\"QUICK_WAP_WAY\"" +
                "  }");//填充业务参数
        String form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();*/
    }

    
    @RequestMapping("newSand")
    public void newSand(HttpServletResponse httpResponse) throws Exception {
       /* AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", "2021000122693637",
                                                            "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCQjiWbf1NcO7o2ivr4boKoDdfz5KVdachNmX4nvvBDtObzlMMM2TmzIYYaLhcffCewaPpVJHIj1RqVFQ/wqUtOkABSAs5kvsvP3UNy3a5LBu3i6kQo1e9wNRkeGHydR4dcWhYbleNobfsJAaAw5SamVFdztR2+b80h0hq1tyMBauO2puWIj8adaN440JvIg6S0I+epWZV8FtgJIE8ZdNb3HtBE0LFm2tJz7VVD7hllNCwy8xyyVP1OX79zYyn6wz/w5DtR6Vwa6Dmk3QCg80iH+MPy8jPpE2781db8tOBvuNPHXN2hrzq97UTJrXSv9+38loOC5FUB92NQVtFPaNmtAgMBAAECggEBAIenvgck/9eofWG+HzOQkbCf/S72PXFiWgTorIkkGFmRpMKlsj2WhR1jsnNTGYQEgUJ94Z6RK0QRMncBYwoX9YHuhT5xP7svihixriBXhL8H66ps6jXgPmjwi3fAxwDaJV83c1PD37saquCS0//Oq+yfbco6B4W1aa35e/NXv9QNT+5KCW2u/8VuJA4ZA15B5a0+AO8kR3BZ3xDvVesXect88hmUPDnmXskuS6jpOMSLbYbhSBnDinAEpaPRrqN5KX2JTdn9yrncttdIquvdOFjQWNoDsKIE4xmZVhuB28iiMzTfL4K2xIC88lqOQckohzc3G1i7UJ6uL88HyCojmUECgYEAyMClI8fLnpCpUflSyXd0L72jcymZ2oxSxNnQzl5M5eyyNw6EwVSLbe6qo+aZeYXKLw8nB8p2XcMKbR8dVaskVL4idZPhsJfIceS3ZnMCxllvVqPBce4HJgv4wJgwnq9Qa7T2VgzL5dU2qsvi9Qm44wqXaRInqqSve/BzeEtDR3kCgYEAuFZPUCbx1m4s33zu8WWK8v9k5hil3t1HdAAbRMgNyg0RhoMZ31ieufYRMpZk8VVJMlW6Ddmk0GWVYiUF9WO1rNMxFE7Ah8qWcwLXB9u0iOqgoUWl2GA9Uou7A8ZLCMHOdmlJRBEaaaYEJu0dFr/V9sIm2j06VUI0cCXsW9BO8tUCgYEAj5AMyMixmcSUAZZOGNs/EIEKaWnfp8XfzvyBcYNIdMjPLcZJM8SVLVmXWDyplpkR3JN2cwDbovO++ghdPw1zntKV7AWESXhSFPjeGvq2ikgc8hWLWkFBhXjcPEbZxjFTTqML4r+l9MeEH6JMvLVmLZ8+ZhpgmYzKHdT3jpgsFekCgYBSS2X5OIm621D5LUNXTafsuAwJlXNnvY4KwYlq+Yz+aTsrvBeu2Fd0WeBvnyjNfO/Covb+++1ShCdeu3yfgrY2w8ojcM0PUmg8TEZHYdSFU4oGtZtGsCBwW6VQGBSjgjJ0NqjY1HHgPJeZ8T2NTHNvSFokEDWcnoPelW+hxauZSQKBgQC8B8s3gKsc4feE8CruYZiik80ggGU2ldYJiFYqHNtcrBf4B0xC4jOBCoWLLl4uoNQrm6RrZIqMJDtEiH4X/uNJHrg7msGjs/sgANGO+ruTpW9UOwwlm84EoG/jShDEQOQlrC53s1LgvcOQlN4pAw5RkNpWZoX0JYiu/MfSaubZ+A==",
                                                            "json","utf-8",
                                                            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkFZcUHFRAURWyARZDIWZN8EpCxTkKsBqzUwukgrokB+MqZjVcg9EQy0H7hl0TrR6K3pflOJsZpiD8SQ3wcMbowY+d2aDj2AePG7+8uov5vyNUKm+NR7UQkL+bXXaYRujt6Y5gItX3yo9VC9/Sur11ah+XGorZWijIJ6BkSDH97XJZq8rmz//iD3ghD4KWEJkGEEDgxAUVCGIC8O0nC8vuJk6QZzMoWtUkm4fI8CUluo5NOd1HI5Y7cT3GD2anFHdjpCZDCqyHDKVQF/tqMVx2cYncgC7D3+D5s97WDZMkqC+SUq7CyflTvuW3D0oLXeZRtEnGNO5VJUqy64VDxukYQIDAQAB",
                                                            "RSA2");*/
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, AlipayConfig.FORMAT,
                                                            AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
    
        request.setNotifyUrl("");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "zdh" + System.currentTimeMillis());
        bizContent.put("total_amount", 0.01);
        bizContent.put("subject", "测试商品");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.put("qr_pay_mode", 2);
    
        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);
    
        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);
    
        //// 结算信息，按需传入
        //JSONObject settleInfo = new JSONObject();
        //JSONArray settleDetailInfos = new JSONArray();
        //JSONObject settleDetail = new JSONObject();
        //settleDetail.put("trans_in_type", "defaultSettle");
        //settleDetail.put("amount", 0.01);
        //settleDetailInfos.add(settleDetail);
        //settleInfo.put("settle_detail_infos", settleDetailInfos);
        //bizContent.put("settle_info", settleInfo);
    
        //// 二级商户信息，按需传入
        //JSONObject subMerchant = new JSONObject();
        //subMerchant.put("merchant_id", "2088000603999128");
        //bizContent.put("sub_merchant", subMerchant);
    
        //// 业务参数信息，按需传入
        //JSONObject businessParams = new JSONObject();
        //businessParams.put("busi_params_key", "busiParamsValue");
        //bizContent.put("business_params", businessParams);
    
        //// 营销信息，按需传入
        //JSONObject promoParams = new JSONObject();
        //promoParams.put("promo_params_key", "promoParamsValue");
        //bizContent.put("promo_params", promoParams);
    
        request.setBizContent(bizContent.toString());
        // AlipayTradePrecreateResponse response = alipayClient.execute(request);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        String form = response.getBody();
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
    
    //支付结果通知
    @PostMapping("/paynotifytest")
    public void paynotify(HttpServletRequest request,HttpServletResponse response) throws IOException, AlipayApiException {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");

        if(verify_result){//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //商户订单号

            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号

            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");


            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                //如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                System.out.println(trade_status);
                //注意：
                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            response.getWriter().write("success");

            //////////////////////////////////////////////////////////////////////////////////////////
        }else{//验证失败
            response.getWriter().write("fail");
        }


    }

}
